package com.bawei.lib_common.mvi

import android.os.Bundle
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bawei.lib_common.base.BaseActivity
import com.bawei.lib_common.event.CustomEvent
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseMviActivity<T:ViewDataBinding>:BaseActivity<T>() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initData()
        updateUI()
        //注册EventBus
        EventBus.getDefault().register(this)
    }

    /**
     * 声明事件接收方法
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveEvent(event:CustomEvent){
        //目标页面的校验
        if(event!=null&&event.target==this::class.java.simpleName){
            handEvent(event)
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        //一定要反注册,避免内存泄漏
        EventBus.getDefault().unregister(this)
    }



    private fun initData(){
        lifecycleScope.launch {
            sendViewIntent()
        }
    }

    private fun updateUI(){
        lifecycleScope.launch {
            //制定在Actyivity执行某一个
          lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
             collectUIState()
          }
        }
    }



    /**
     * 子类可以有选择性重写该方法
     */
    open suspend fun sendViewIntent(){

    }

    open suspend fun collectUIState(){

    }

    open  fun handEvent(event:CustomEvent){

    }
}